module.exports = {
	/**
	 * 查询角色列表
	 * @url client/wechat/selects/pub/selects 前端调用的url参数地址
	 * 表名
	 * @dbName 查询的表的名称
	 * data 请求参数 说明
	 * @param {String}         _id  用户编号
	 * res 返回参数说明
	 * @param {Number}         code      错误码，0表示成功
	 * @param {String}         msg       详细信息
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {_id,type,comment} = data;
		
		let { todayStart, todayEnd } = vk.pubfn.getCommonTime();
		//查询应该获得/扣除积分
		var signScore = await vk.baseDao.findByWhereJson({
			dbName: 'bus-wx-config',
			whereJson: {
				config_key: 'score_config'
			}
		});
		let score = 0
		if(type === 'invited'){
			// 邀请获得积分
			if(signScore.invite_num > 0){
				let num = await vk.baseDao.count({
					dbName:"uni-id-scores",
					whereJson:{
						user_id: _id,
						comment: new RegExp('^'+'邀请用户'),
						_add_time: _.gte(todayStart).lte(todayEnd)
					}
				});
				if(num >= signScore.invite_num){
					return {
						code: 0
					}
				}
			}
			score = signScore.invite_score
		}else if(type === 'video'){
			// 看视频获得积分
			if(signScore.video_num > 0){
				let num = await vk.baseDao.count({
					dbName:"uni-id-scores",
					whereJson:{
						user_id: _id,
						comment: new RegExp('^'+'观看视频广告'),
						_add_time: _.gte(todayStart).lte(todayEnd)
					}
				});
				if(num >= signScore.video_num){
					return {
						code: -1,
						msg: '今日次数已达上限'
					}
				}
			}
			score = signScore.video_score
		}
		
		if(score > 0){
			// 执行数据库API请求
			var user = await vk.baseDao.updateById({
				dbName: "uni-id-users",
				id: _id,
				dataJson: {
					score: _.inc(score)
				},
				getUpdateData:true
			});
			if(!user){
				res.code = -1
				res.msg = "积分操作失败"
				return res;
			}
			
			var scoreNum = await vk.baseDao.add({
				dbName: "uni-id-scores",
				dataJson: {
					user_id: _id,
					type: score>0?1:2,
					score: score>0?score:-score,
					balance: user.score,
					comment: comment
				}
			});
			
			res.user = user
		}
		res.score = score
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}

}